/**
 * Created by Administrator on 2014/8/19.
 */
var request = require('request');
var wxConfig = require('../config/wx');
var wxApi = 'https://api.weixin.qq.com/cgi-bin';
var getTokenUrl =wxApi + '/token?grant_type=client_credential' +
    '&appid=' + wxConfig.appId + '&secret=' + wxConfig.appSecret;

var accessToken = '';

function updateAccessToken(next,back){
    request(getTokenUrl, function (err, res, body) {
        if (!err && res.statusCode == 200) {
            var result = JSON.parse(body);
            accessToken = result.access_token;
            console.log('微信access-token更新成功');
            var nextUpdateTime = (result.expires_in - 30) * 1000;
            setTimeout(updateAccessToken,nextUpdateTime);
            if(next){
                next(accessToken);
            }
        }else{
            console.log('微信access-token获取异常');
            console.log(err);
            if(back){
                back(err);
            }
        }
    });
}

exports.init = function(next,back){
    updateAccessToken(next,back);
}

exports.getAccessToken = function(){
    return accessToken;
}

//使用code换取accessToken和openId
//TODO这个地方还会同时获得一个refreshToken当accessToken超时后可以使用refreshToken刷新
exports.changeAccessToken = function(code,next,back){
    var changeAccessTokenUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?'
        + 'appid=' + wxConfig.appId + '&secret=' + wxConfig.appSecret
        + '&code=' + code + '&grant_type=authorization_code';
    request(changeAccessTokenUrl,function(err,res,body){
       if(!err && res.statusCode == 200){
           var result = JSON.parse(body);
           console.log('向微信服务器交换accessToken成功');
           console.log(result);
           next(result);
       }else{
           console.log('通过code向微信服务器交换accessToken异常');
           console.log(err);
           back(err);
       }
    });
}

//获得用户信息 昵称，性别，省份，国家，头像，以及用户特权信息
exports.getUserInfo = function(accessToken,openId,next,back){
    var getUserInfoUrl = 'https://api.weixin.qq.com/sns/userinfo?'
        +  'access_token=' + accessToken + '&openid=' + openId + '&lang=zh_CN';
    request(getUserInfoUrl,function(err,res,body){
        if(!err && res.statusCode == 200){
            var result = JSON.parse(body);
            console.log('获取用户信息成功');
            console.log(result);
            next(result);
        }else{
            console.log('获取用户信息异常');
            console.log(err);
            back(err);
        }
    });
}
